<template>
  <div>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="layui-row">
        <div
          v-if="isSysGroup"
          class="select-depot-storage"
          :class="isSysGroup ? 'layui-col-md6' : 'layui-col-md12'"
        >
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="leftFilterInfo.query.queryMap"
            :queryMoreJson="true"
            :filter-list="leftFilterInfo.searchList"
            :filter-btn="leftFilterInfo.searchBtn"
          >
          </NewPageFilter>
          <DialogTable
            :refresh="leftTableInfo.refresh"
            :init-curpage="leftTableInfo.initCurpage"
            v-model:data="leftTableInfo.data"
            :api="leftTableInfo.api"
            ref="productTable"
            class="productTable"
            :pager="false"
            :reserveSelection="true"
            :listenHeight="false"
            :selectable="selectable"
            :query="leftFilterInfo.query"
            :field-list="leftTableInfo.fieldList"
            :highlight-row="isSysGroup ? highlightRow : false"
            :check-box="checkBox"
            :is-row-click-select="!isSysGroup"
            @handleEvent="leftHandleEvent"
          >
          </DialogTable>
        </div>
        <div
          class="select-depot-storage"
          :class="isSysGroup ? 'layui-col-md6' : 'layui-col-md12'"
          style="padding-left: 20px"
        >
          <NewPageFilter
            v-model:query="rightFilterInfo.query.queryMap"
            :queryMoreJson="true"
            :filter-list="rightFilterInfo.searchList"
            :filter-btn="rightFilterInfo.searchBtn"
          >
          </NewPageFilter>
          <el-form ref="tableForm" :model="rightTableInfo" style="width: 100%">
            <DialogTable
              :refresh="rightTableInfo.refresh"
              :init-curpage="rightTableInfo.initCurpage"
              v-model:data="rightTableInfo.data"
              :api="rightTableInfo.api"
              ref="batchNumberTable"
              :reserveSelection="true"
              :listenHeight="false"
              :query="rightFilterInfo.query"
              :field-list="rightTableInfo.fieldList"
              :check-box="checkBox"
              :handle="rightTableInfo.handle"
              :pager="false"
              :row-class-name="tableRowClassName"
              @handleEvent="rightHandleEvent"
            >
              <template v-slot:col-editQty="scope">
                <el-form-item class="margin-bottom" @click.stop="">
                  <div
                    v-if="scope.row.codeType === 1 || scope.row.codeType === 4"
                    class="page-table-input-number-wrapper"
                  >
                    <div class="page-table-input-number-left">
                      <div class="page-table-input-number-item">
                        <el-form-item
                          :prop="`data.${scope.$index}.largeUnitQty`"
                          :rules="scope.$index >= 0 ? [
                            {
                              validator: $validate.positiveAndZero,
                              trigger: 'blur',
                            },
                          ] : []"
                        >
                          <el-input-number
                            v-model.lazy="scope.row.largeUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="
                              scope.row.qtyOperateMode === 0 ||
                              scope.row.qtyOperateMode === 2
                                ? 0
                                : systemConfig.qty_show_precision
                            "
                            :min="0"
                            :max="largeMax(scope.row)"
                            @change="
                              changeLarge(
                                $event,
                                scope.row,
                                `data.${scope.$index}.largeUnitQty`
                              )
                            "
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.unitName }}
                        </div>
                      </div>
                      <div
                        v-if="
                          scope.row.unitConvertCoefficient > 1 &&
                          scope.row.qtyOperateMode === 2
                        "
                        class="page-table-input-number-item"
                      >
                        <el-form-item>
                          <el-input-number
                            v-model.lazy="scope.row.smallUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="0"
                            :min="0"
                            :max="smallMax(scope.row)"
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.calcUnitName }}
                        </div>
                      </div>
                    </div>
                    <div
                      v-if="scope.row.qtyOperateMode === 2"
                      class="page-table-input-number-right"
                    >
                      {{ $fn.qtyFormatter(scope.row.editQty) }}
                    </div>
                  </div>
                  <template
                    v-else-if="
                      scope.row.codeType === 2 || scope.row.codeType === 3
                    "
                  >
                    <span class="qty-show">
                      {{ $fn.qtyFormatter(scope.row.editQty) }}
                    </span>
                  </template>
                </el-form-item>
              </template>
              <template v-slot:col-editRefuseQty="scope">
                <el-form-item class="margin-bottom" @click.stop="">
                  <div
                    v-if="scope.row.codeType === 1 || scope.row.codeType === 4"
                    class="page-table-input-number-wrapper"
                  >
                    <div class="page-table-input-number-left">
                      <div class="page-table-input-number-item">
                        <el-form-item
                          :prop="`data.${scope.$index}.refuseLargeUnitQty`"
                          :rules="scope.$index >= 0 ? [
                            {
                              validator: $validate.positiveAndZero,
                              trigger: 'blur',
                            },
                          ] : []"
                        >
                          <el-input-number
                            v-model.lazy="scope.row.refuseLargeUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="
                              scope.row.qtyOperateMode === 0 ||
                              scope.row.qtyOperateMode === 2
                                ? 0
                                : systemConfig.qty_show_precision
                            "
                            :min="0"
                            :max="refuseLargeMax(scope.row)"
                            @change="
                              refuseChangeLarge(
                                $event,
                                scope.row,
                                `data.${scope.$index}.refuseLargeUnitQty`
                              )
                            "
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.unitName }}
                        </div>
                      </div>
                      <div
                        v-if="
                          scope.row.unitConvertCoefficient > 1 &&
                          scope.row.qtyOperateMode === 2
                        "
                        class="page-table-input-number-item"
                      >
                        <el-form-item>
                          <el-input-number
                            v-model.lazy="scope.row.refuseSmallUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="0"
                            :min="0"
                            :max="refuseSmallMax(scope.row)"
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.calcUnitName }}
                        </div>
                      </div>
                    </div>
                    <div
                      v-if="scope.row.qtyOperateMode === 2"
                      class="page-table-input-number-right"
                    >
                      {{ $fn.qtyFormatter(scope.row.editRefuseQty) }}
                    </div>
                  </div>
                  <template
                    v-else-if="
                      scope.row.codeType === 2 || scope.row.codeType === 3
                    "
                  >
                    <span class="qty-show">
                      {{ $fn.qtyFormatter(scope.row.editRefuseQty) }}
                    </span>
                  </template>
                </el-form-item>
              </template>
              <template v-slot:bt-switch="scope">
                <el-switch
                  v-if="
                    scope.data.row.codeType === 2 ||
                    scope.data.row.codeType === 3
                  "
                  v-model="scope.data.row.receiveFlag"
                  inactive-text="拒"
                  active-text="收"
                  @change="changeQtySwitch($event, scope.data.row)"
                  @click.stop=""
                ></el-switch>
              </template>
            </DialogTable>
          </el-form>
        </div>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="selectProduct">
import PageDialog from '@/components/PageDialog/index'
import DialogTable from '@/components/DialogTable/index'

import { getDepotStockCustomizeListPage } from '@/api/stock.js'
import { getCustomizeSetting } from '@/api/customize'

import * as _ from 'lodash'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: true,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getDepotStockCustomizeListPage,
  },
  excludeQueryList: {
    type: Array,
    default: function () {
      return []
    },
  },
  showPrice: {
    type: Boolean,
  },
  showDialog: {
    type: Boolean,
  },
  leftTableKey: {
    type: String,
    default: '',
  },
  rightTableKey: {
    type: String,
    default: '',
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  queryParams: {
    type: Object,
    default: function () {
      return {}
    },
  },
})

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const selectRow = ref([])
const clickRow = ref({})
const clickRowMap = ref(new Map())
const selectBatchRow = ref(new Map())
// 过滤相关配置
const isSysGroup = ref(false)
const leftFilterInfo = reactive({
  query: {
    queryMap: {},
    customizeUserVO: {},
    queryParams: props.queryParams,
  },
  searchList: [],
  searchBtn: [{ type: 'button', label: '搜索', event: leftSearch }],
})
const searchObj = ref('')
const groupArr = ref('')
// 表格相关
const leftTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  height: '70%',
  data: [],
  fieldList: [],
})
const rightFilterInfo = reactive({
  query: {
    queryMap: {},
    customizeUserVO: {},
    queryParams: props.queryParams,
  },
  searchList: [],
  searchBtn: [{ type: 'button', label: '搜索', event: rightSearch }],
})
// 表格相关
const rightTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  height: '70%',
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '开关',
        name: 'switch',
        slot: true,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = reactive({
  title: '添加产品',
  btLoading: false,
  width: '90%',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: true,
      event: save,
      show: true,
    },
  ],
})
const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})
watch(
  () => rightTableInfo.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        let smallUnitQty = row.smallUnitQty || 0
        let refuseSmallUnitQty = row.refuseSmallUnitQty || 0
        let unitConvertCoefficient = row.unitConvertCoefficient || 1
        let largeUnitQty = row.largeUnitQty || 0
        let refuseLargeUnitQty = row.refuseLargeUnitQty || 0
        let editCalcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let editRefuseCalcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(refuseLargeUnitQty, unitConvertCoefficient),
          refuseSmallUnitQty
        )
        let editQty = proxy.$fn.accDiv(editCalcQty, unitConvertCoefficient)
        let editRefuseQty = proxy.$fn.accDiv(
          editRefuseCalcQty,
          unitConvertCoefficient
        )
        row['editCalcQty'] = editCalcQty
        row['editQty'] = editQty
        row['editRefuseCalcQty'] = editRefuseCalcQty
        row['editRefuseQty'] = editRefuseQty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(editCalcQty, row.price),
          unitConvertCoefficient
        )
        let newData = ''
        if (isSysGroup.value) {
          let key = setKey(clickRow.value)
          newData = selectBatchRow.value.get(key)
          if (newData && newData.length) {
            newData.forEach((item) => {
              if (item.id === row.id) {
                item.largeUnitQty = row.largeUnitQty
                item.smallUnitQty = row.smallUnitQty
                item.editCalcQty = row.editCalcQty
                item.editQty = row.editQty
                item.sumAmount = row.sumAmount

                item.editRefuseCalcQty = row.editRefuseCalcQty
                item.editRefuseQty = row.editRefuseQty
                item.refuseSmallUnitQty = row.refuseSmallUnitQty
                item.refuseLargeUnitQty = row.refuseLargeUnitQty
                item.receiveFlag = row.receiveFlag
              }
            })
            let key = setKey(clickRow.value)
            selectBatchRow.value.set(key, newData)
          }
        }
      })
    }
  },
  {
    deep: true,
  }
)

let obj = {
  price: {
    label: '单价',
    value: 'price',
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    componentType: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    permission: !props.showPrice,
    hidden: true,
    show: false,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  defaultPrice: {
    label: '默认价格',
    value: 'defaultPrice',
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
}
leftTableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
rightTableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  editQty: {
    label: '数量',
    value: 'editQty',
    type: 'slot',
    componentType: 'number',
    show: false,
    hidden: true,
    minWidth: '250px',
  },
  editRefuseQty: {
    label: '拒收数量',
    value: 'editRefuseQty',
    type: 'slot',
    componentType: 'number',
    show: false,
    hidden: true,
    minWidth: '250px',
  },
})
rightFilterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
leftFilterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
getLeftCustomize()

function changeQtySwitch(e, row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  if (e) {
    if (row.qtyOperateMode === 2) {
      row.largeUnitQty = parseInt(
        row.pendReceiveCalcQty / unitConvertCoefficient
      )
      row.smallUnitQty = parseInt(
        row.pendReceiveCalcQty % unitConvertCoefficient
      )
    } else {
      row.largeUnitQty = row.pendReceiveCalcQty
      row.smallUnitQty = 0
    }

    row.refuseLargeUnitQty = 0
    row.refuseSmallUnitQty = 0
  } else {
    if (row.qtyOperateMode === 2) {
      row.refuseLargeUnitQty = parseInt(
        row.pendReceiveCalcQty / unitConvertCoefficient
      )
      row.refuseSmallUnitQty = parseInt(
        row.pendReceiveCalcQty % unitConvertCoefficient
      )
    } else {
      row.refuseLargeUnitQty = row.pendReceiveCalcQty
      row.refuseSmallUnitQty = 0
    }
    row.largeUnitQty = 0
    row.smallUnitQty = 0
  }
}
function refuseChangeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let refuseLargeUnitQty = parseInt(
    row.pendReceiveCalcQty / row.unitConvertCoefficient
  )

  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (refuseLargeUnitQty > 0 && e === refuseLargeUnitQty) {
      let refuseSmallUnitQty = parseInt(
        row.pendReceiveCalcQty % row.unitConvertCoefficient
      )
      if (row.refuseSmallUnitQty > refuseSmallUnitQty) {
        row.refuseSmallUnitQty = refuseSmallUnitQty
      }
    }
  }
}
function refuseLargeMax(row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  if (row.qtyOperateMode === 2) {
    return parseInt(row.pendReceiveCalcQty / unitConvertCoefficient)
  } else {
    return row.pendReceiveQty
  }
}
function refuseSmallMax(row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  let refuseLargeUnitQty = parseInt(
    row.pendReceiveCalcQty / unitConvertCoefficient
  )
  if (
    refuseLargeUnitQty === 0 ||
    row.refuseLargeUnitQty === refuseLargeUnitQty
  ) {
    return parseInt(row.pendReceiveCalcQty % unitConvertCoefficient)
  } else {
    return unitConvertCoefficient - 1
  }
}
function smallMax(row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  let largeUnitQty = parseInt(row.pendReceiveCalcQty / unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.pendReceiveCalcQty % unitConvertCoefficient)
  } else {
    return unitConvertCoefficient - 1
  }
}
// 数量操作模式 qtyOperateMode：0整数模式，2自动算出小数，1手动输入小数
// 条码类型 code_type：1无码，2系统唯一码，3原厂码，4批次码
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.pendReceiveCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.pendReceiveCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function largeMax(row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  if (row.qtyOperateMode === 2) {
    return parseInt(row.pendReceiveCalcQty / unitConvertCoefficient)
  } else {
    return row.pendReceiveQty
  }
}
// 获取左侧产品列表
function getLeftList() {
  proxy.$nextTick(() => {
    leftTableInfo.value.refresh = Math.random()
  })
}
function leftSearch() {
  proxy.$nextTick(() => {
    leftTableInfo.value.initCurpage = Math.random()
    leftTableInfo.value.refresh = Math.random()
  })
}
function getRightList() {
  proxy.$nextTick(() => {
    rightTableInfo.refresh = Math.random()
  })
}
function rightSearch() {
  proxy.$nextTick(() => {
    rightTableInfo.initCurpage = Math.random()
    rightTableInfo.refresh = Math.random()
  })
}
function selectable() {
  if (isSysGroup.value) {
    return false
  } else {
    return true
  }
}
function save() {
  //条码类型 code_type：1无码，2系统唯一码，3原厂码，4批次码
  let selectRows = []
  if (isSysGroup.value) {
    let keyArr = [...clickRowMap.value.keys()]
    let valueArr = [...clickRowMap.value.values()]
    keyArr.forEach((item, index) => {
      let details = selectBatchRow.value.get(item)
      let obj = setDetails(details)
      valueArr[index].isChoice = true
      valueArr[index].details = obj.data
      valueArr[index].sumAmount = obj.sumAmount
    })
    selectRows = valueArr
  } else {
    let obj = setDetails(selectRow.value)
    selectRows = obj.data
  }
  let detailsArr = []
  if (isSysGroup.value) {
    selectRows.forEach((row) => {
      detailsArr = row.details.filter(
        (item) => item.qty > 0 || item.refuseQty > 0
      )
    })
  } else {
    detailsArr = selectRows.filter(
      (item) => item.qty > 0 || item.refuseQty > 0
    )
  }

  if (detailsArr.length) {
    let itemList = detailsArr.filter(
      (item) =>
        proxy.$fn.accAdd(item.editCalcQty || 0, item.editRefuseCalcQty) >
        item.pendReceiveCalcQty
    )
    if (itemList.length > 0) {
      proxy.$alert(
        `操作的个体的数量与拒收数量之和不能大于待收货数量`,
        '操作提示',
        {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
        }
      )
      return
    }
  }

  handleClose()
  emit('callback', selectRows)
}
function setDetails(data) {
  let sumAmount = 0
  data.forEach((item) => {
    item.isChoice = true
    if (item.qtyOperateMode === 2) {
      if (item.codeType == 1 || item.codeType == 4) {
        if (item.pendReceiveCalcQty < item.unitConvertCoefficient) {
          item.calcQty =
            item.editCalcQty || item.editRefuseCalcQty
              ? item.editCalcQty
              : item.pendReceiveCalcQty
          item.qty =
            item.editQty || item.editRefuseQty
              ? item.editQty
              : item.pendReceiveQty
          item.refuseQty = item.editRefuseQty
          item.refuseCalcQty = item.editRefuseCalcQty

          item.largeUnitQty = 0
          item.smallUnitQty = parseInt(
            item.pendReceiveCalcQty % item.unitConvertCoefficient
          )
          item.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(item.calcQty, item.price),
            item.unitConvertCoefficient
          )
        } else {
          item.calcQty =
            item.editCalcQty || item.editRefuseCalcQty
              ? item.editCalcQty
              : item.unitConvertCoefficient
          item.qty = item.editQty || item.editRefuseQty ? item.editQty : 1
          item.largeUnitQty =
            item.editQty || item.editRefuseQty ? item.editQty : 1
          item.refuseQty = item.editRefuseQty
          item.refuseCalcQty = item.editRefuseCalcQty
          item.smallUnitQty = 0
          item.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(item.calcQty, item.price),
            item.unitConvertCoefficient
          )
        }
      } else if (item.codeType == 2 || item.codeType == 3) {
        item.calcQty =
          item.editCalcQty || item.editRefuseCalcQty
            ? item.editCalcQty
            : item.pendReceiveCalcQty
        item.qty =
          item.editQty || item.editRefuseQty
            ? item.editQty
            : item.pendReceiveQty
        item.refuseQty = item.editRefuseQty
        item.refuseCalcQty = item.editRefuseCalcQty
        item.receiveFlag = true
        item.largeUnitQty = parseInt(
          item.pendReceiveCalcQty / item.unitConvertCoefficient
        )
        item.smallUnitQty = parseInt(
          item.pendReceiveCalcQty % item.unitConvertCoefficient
        )
        item.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(item.calcQty, item.price),
          item.unitConvertCoefficient
        )
      }
    } else {
      if (item.pendReceiveCalcQty < item.unitConvertCoefficient) {
        item.calcQty =
          item.editCalcQty || item.editRefuseCalcQty
            ? item.editCalcQty
            : item.pendReceiveCalcQty
        item.qty =
          item.editQty || item.editRefuseQty
            ? item.editQty
            : item.pendReceiveQty
        item.refuseQty = item.editRefuseQty
        item.refuseCalcQty = item.editRefuseCalcQty
        item.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(item.calcQty, item.price),
          item.unitConvertCoefficient
        )
      } else {
        item.calcQty =
          item.editCalcQty || item.editRefuseCalcQty
            ? item.editCalcQty
            : item.unitConvertCoefficient
        item.qty = item.editQty || item.editRefuseQty ? item.editQty : 1
        item.largeUnitQty =
          item.editQty || item.editRefuseQty ? item.editQty : 1
        item.refuseQty = item.editRefuseQty
        item.refuseCalcQty = item.editRefuseCalcQty
        item.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(item.calcQty, item.price),
          item.unitConvertCoefficient
        )
      }
      item.smallUnitQty = 0
    }
    sumAmount = proxy.$fn.accDiv(sumAmount, item.sumAmount || 0)
  })
  return { data: data, sumAmount: sumAmount }
}
function leftHandleEvent(event, data) {
  if (!isSysGroup.value) {
    if (event === 'tableCheck' && data.length) {
      selectRow.value = data
      dialogInfo.btList[1].disabled = false
    } else {
      dialogInfo.btList[1].disabled = true
    }
    return
  }
  switch (event) {
    case 'tableClickRow':
      if (data && data.id) {
        let newData = proxy.$fn.deepClone(data)
        newData.key = setKey(newData)
        clickRow.value = data
        for (let key in searchObj.value) {
          searchObj.value[key].value = newData[key]
        }
        rightFilterInfo.query.queryMap = {
          ...rightFilterInfo.query.queryMap,
          ...searchObj.value,
        }
        rightTableInfo.api = props.api
        rightSearch()
        let key = setKey(clickRow.value)
        clickRowMap.value.set(key, data)
        if (!selectBatchRow.value.has(key)) {
          console.log(proxy.$refs['productTable'])
          proxy.$refs['productTable'].toggleRowSelection(
            clickRow.value,
            true
          )
        }
      }
      break
  }
}
function setKey(item) {
  let key = ''
  groupArr.value && groupArr.value.forEach((row, index) => {
    key =
      key + item[row.value] + (index === groupArr.value.length - 1 ? '' : '&')
  })
  return key
}
function rightHandleEvent(event, data) {
  switch (event) {
    case 'list':
      if (data.length) {
        let key = setKey(clickRow.value)
        let selectData
        if (isSysGroup.value) {
          selectData = selectBatchRow.value.get(key)
        } else {
          selectData = selectRow.value
        }
        data.forEach((row) => {
          if (row.codeType === 1 || row.codeType === 4) {
            row.largeUnitQty = 0
            row.smallUnitQty = 0
            row.sumAmount = 0
            // row.editCalcQty = 1;
            // row.editQty = 1;
          } else if (row.codeType === 2 || row.codeType === 3) {
            // row.largeUnitQty = 1;
            row.editCalcQty = row.calcQty
            row.editQty = row.qty
            // row.receiveFlag = true;
          }

          if (selectData && selectData.length) {
            selectData.forEach((item) => {
              if (item.id === row.id) {
                row.largeUnitQty = item.largeUnitQty
                row.smallUnitQty = item.smallUnitQty
                row.editCalcQty = item.editCalcQty
                row.editQty = item.editQty
                row.sumAmount = item.sumAmount
                row.editRefuseCalcQty = item.editRefuseCalcQty
                row.editRefuseQty = item.editRefuseQty
                row.refuseSmallUnitQty = item.refuseSmallUnitQty
                row.refuseLargeUnitQty = item.refuseLargeUnitQty
                row.receiveFlag = item.receiveFlag
              }
            })
          }
        })
        rightTableInfo.data = data
        if (!selectBatchRow.value.has(key) && isSysGroup.value) {
          if ([...selectBatchRow.value.keys()].length) {
            if (!selectBatchRow.value.has(setKey(data[0]))) {
              proxy.$refs['batchNumberTable'].toggleRowSelection(
                data[0],
                true
              )
            }
          } else {
            proxy.$refs['batchNumberTable'].toggleRowSelection(
              data[0],
              true
            )
          }
        }
      }

      break
    case 'tableCheck':
      if (data && data.length) {
        data.forEach((item) => {
          if (!item.editCalcQty && !item.editRefuseCalcQty) {
            if (item.qtyOperateMode === 2) {
              if (item.codeType == 1 || item.codeType == 4) {
                if (item.pendReceiveCalcQty < item.unitConvertCoefficient) {
                  item.editQty = item.pendReceiveQty
                  item.editCalcQty = item.pendReceiveCalcQty
                  item.largeUnitQty = 0
                  item.smallUnitQty = parseInt(
                    item.pendReceiveCalcQty % item.unitConvertCoefficient
                  )
                  item.sumAmount = proxy.$fn.accDiv(
                    proxy.$fn.accMul(item.calcQty, item.price),
                    item.unitConvertCoefficient
                  )
                } else {
                  item.editQty = 1
                  item.editCalcQty = item.unitConvertCoefficient
                  item.largeUnitQty = 1
                  // item.qty = 1;
                  // item.calcQty = item.unitConvertCoefficient;
                  // item.largeUnitQty = 1;

                  item.smallUnitQty = 0
                  item.sumAmount = proxy.$fn.accDiv(
                    proxy.$fn.accMul(item.calcQty, item.price),
                    item.unitConvertCoefficient
                  )
                }
              } else if (item.codeType == 2 || item.codeType == 3) {
                item.editQty = item.pendReceiveQty
                item.editCalcQty = item.pendReceiveCalcQty
                // item.qty = item.pendReceiveQty;
                item.receiveFlag = true
                // item.calcQty = item.pendReceiveCalcQty;
                item.largeUnitQty = parseInt(
                  item.pendReceiveCalcQty / item.unitConvertCoefficient
                )
                item.smallUnitQty = parseInt(
                  item.pendReceiveCalcQty % item.unitConvertCoefficient
                )
                item.sumAmount = proxy.$fn.accDiv(
                  proxy.$fn.accMul(item.calcQty, item.price),
                  item.unitConvertCoefficient
                )
              }
            } else {
              if (item.pendReceiveCalcQty < item.unitConvertCoefficient) {
                item.editQty = item.pendReceiveQty
                item.editCalcQty = item.pendReceiveCalcQty
                // item.qty = item.pendReceiveQty;
                // item.calcQty = item.pendReceiveCalcQty;
                item.largeUnitQty = item.pendReceiveCalcQty
                item.sumAmount = proxy.$fn.accDiv(
                  proxy.$fn.accMul(item.calcQty, item.price),
                  item.unitConvertCoefficient
                )
              } else {
                item.editQty = 1
                item.editCalcQty = item.unitConvertCoefficient
                item.largeUnitQty = 1

                item.sumAmount = proxy.$fn.accDiv(
                  proxy.$fn.accMul(item.calcQty, item.price),
                  item.unitConvertCoefficient
                )
              }
              if (item.codeType == 2 || item.codeType == 3) {
                item.receiveFlag = true
              }
              item.smallUnitQty = 0
            }
          }
        })
      }

      if (!isSysGroup.value) {
        selectRow.value = data
      } else {
        if (data.length) {
          let mapNew = _.groupBy(data, (item) => {
            let key = setKey(item)
            return key
          })
          let key = setKey(clickRow.value)
          if (!Object.keys(mapNew).includes(key)) {
            selectBatchRow.value.delete(key)
            clickRowMap.value.delete(key)
            proxy.$refs['productTable'].toggleRowSelection(
              clickRow.value,
              false
            )
            proxy.$refs['productTable'].setCurrentRow()
          } else {
            clickRowMap.value.set(key, clickRow.value)
            proxy.$refs['productTable'].toggleRowSelection(
              clickRow.value,
              true
            )
            for (let key in mapNew) {
              selectBatchRow.value.set(key, mapNew[key])
            }
          }
        } else {
          let key = setKey(clickRow.value)
          selectBatchRow.value.delete(key)
          clickRowMap.value.delete(key)
          proxy.$refs['productTable'].toggleRowSelection(
            clickRow.value,
            false
          )
        }
      }

      break
  }
  let len = isSysGroup.value
    ? [...selectBatchRow.value.keys()].length
    : selectRow.value.length
  if (len) {
    dialogInfo.btList[1].disabled = false
  } else {
    dialogInfo.btList[1].disabled = true
  }
}
function tableRowClassName({ row }) {
  if (
    proxy.$fn.accAdd(row.editCalcQty, row.editRefuseCalcQty) >
    row.pendReceiveCalcQty
  ) {
    return 'warning-row'
  }
  if (row.isChoice) {
    return 'success-row'
  }
  return ''
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
function getLeftCustomize() {
  let param = { tableKey: props.leftTableKey }
  let obj = {}
  let groupArrList = []
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      leftFilterInfo.query.customizeUserVO = data
      leftTableInfo.value.fieldList = proxy.$fn.setFieldList(
        leftTableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        leftFilterInfo.searchList,
        data.detail
      )
      leftFilterInfo.searchList = searchInfo.searchList
      leftFilterInfo.searchList.forEach((item) => {
        item.event = leftSearch
      })
      isSysGroup.value = false
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          obj[key] = {
            queryType: 'EQUALS',
            queryCategory: 'AND',
            ignoreEmptyValue: false,
            value: null,
          }
          groupArrList.push({ value: key })
          isSysGroup.value = true
        }
      }
      searchObj.value = obj
      groupArr.value = groupArrList
      leftFilterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...props.query,
      }
      leftFilterInfo.query.queryParams.pendReceiveGtZero = true
      if (isSysGroup.value) {
        leftFilterInfo.query.excludeQueryList = props.excludeQueryList
      } else {
        rightFilterInfo.query.excludeQueryList = props.excludeQueryList
      }
      leftTableInfo.value.api = props.api
      getRightCustomize()
      if (isSysGroup.value) {
        leftTableInfo.refresh = Math.random()
        setTimeout(() => {
          getLeftList()
        }, 0);

      }
    }
  })
}
function getRightCustomize() {
  let param = { tableKey: props.rightTableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      rightFilterInfo.query.customizeUserVO = data
      rightTableInfo.fieldList = proxy.$fn.setFieldList(
        rightTableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        rightFilterInfo.searchList,
        data.detail
      )
      rightFilterInfo.searchList = searchInfo.searchList
      rightFilterInfo.searchList.forEach((item) => {
        item.event = leftSearch
      })
      rightFilterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...props.query,
      }
      rightFilterInfo.query.queryParams.pendReceiveGtZero = true
      if (!isSysGroup.value) {
        rightTableInfo.api = props.api
        getRightList()
      }
    }
  })
}
</script>

<style scoped lang="scss">
.productTable :deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
.productTable
  :deep(.el-checkbox__input.is-disabled.is-checked)
  .el-checkbox__inner {
  background-color: #6dc1a9;
  border-color: #6dc1a9;
}
.productTable
  :deep(.el-checkbox__input.is-disabled.is-checked)
  .el-checkbox__inner::after {
  border-color: #ffffff;
}
</style>
